import { defineStore } from 'pinia'
import type {
  loginFormData,
  userInfoResponseDate,
  loginResponseData,
} from '@/api/user/type'
import { reqLogin, reqUserInfo, reqLogOut } from '@/api/user'
import type { UserState } from './types/types'
import { set_Token, get_Token, remove_Token } from '../../utils/token'
import { constantRoute } from '@/router/routes'
let userStore = defineStore('User', {
  state: (): UserState => {
    return {
      token: get_Token(),
      // 菜单需要
      menuRoutes: constantRoute,
      username: '',
      avatar: '',
    }
  },
  actions: {
    async login(data: loginFormData) {
      let result: loginResponseData = await reqLogin(data)
      console.log(result)
      if (result.code == 200) {
        // 断言
        this.token = result.data as string
        // localStorage.setItem("VTtoken", (result.data.token as string))
        set_Token(result.data as string)
        // 让async返回一个成功的函数
        return 'OK'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    async userInfo() {
      // let result: userInfoResponseDate = await reqUserInfo();
      // if (result.code == 200) {
      this.username = 'XGQ'
      this.avatar =
        'http://sd0itu1mm.hn-bkt.clouddn.com/travel/%E4%B8%8A%E6%B5%B7.jpg'
      // } else {
      //   return Promise.reject(new Error(result.message));
      // }
    },
    async userLoginOut() {
      let result: any = await reqLogOut()
      if (result.code == 200) {
        this.username = ''
        this.avatar = ''
        this.token = ''
        remove_Token()
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
  },
  getters: {},
})

export default userStore
